<!--
 * @Author: anshengtyp
 * @Date: 2024-01-10 17:15:42
 * @LastEditTime: 2024-01-10 17:21:53
 * @LastEditors: anshengtyp
 * @Description:
-->
<!-- 技术设计 -->
<template v-if="refreshPage">
  <div class="technicalDesign" v-loading="pageLoading">
    <el-form style="padding: 20px;" ref="form" :model="form" label-width="100px" :rules="rules">
      <!-- 发起 -->
      <template>
        <el-row>
          <el-col :span="12">
            <el-form-item label="技术设计书：">
              <el-upload :auto-upload="false" action="javascript:void(0)" :disabled="sqrNode" :on-remove="handleRemove"
                :file-list="fileList" :on-change="handleChange" :on-preview="downLoad">
                <el-button :disabled="sqrNode" size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上传部门：" prop="promoterDeptId">
              <treeselect :disabled="true" v-model="form.promoterDeptId" :options="deptTreeList" :normalizer="normalizer"
                placeholder="选择部门" />
            </el-form-item>
            <el-form-item label="上传人：" prop="promoterId">
              <el-select :disabled="true" filterable v-model="form.promoterId" placeholder="请选择" style="width: 100%;">
                <el-option v-for="  item   in userList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="上传时间：">
              <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" :disabled="true" v-model="form.requestTime" type="date"
                style="width: 100%;" placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item prop="remark" label="备注">
              <el-input :disabled="sqrNode" type="textarea" v-model="form.remark" placeholder="请输入" :rows="4"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <!-- 生产部门负责人审批 -->
      <template v-if="$hasPermission(['task:jsgl:scbmfzr']) && this.currentStatus">
        <el-row style="margin-top: 30px;">
          <el-col :span="24">
            <el-form-item label="生产部门负责人审批意见：" prop="scbmOptions">
              <el-input :disabled="scbmNode" type="textarea" v-model="form.scbmOptions" placeholder="请输入"
                :rows="4"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="" prop="scbmStatus">
              <el-radio-group :disabled="scbmNode" v-model="form.scbmStatus">
                <el-radio :label="'1'">同意</el-radio>
                <el-radio :label="'2'">不同意</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人：" prop="scbmUserId">
              <el-select ref="scbmUserId" :disabled="scbmNode" filterable v-model="form.scbmUserId" placeholder="请选择"
                style="width: 100%;">
                <el-option v-for="   item    in    userList   " :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审批时间" prop="scbmTime">
              <el-date-picker :disabled="scbmNode" value-format="yyyy-MM-dd HH:mm:ss" v-model="form.scbmTime" type="date"
                style="width: 100%;" placeholder="选择日期时间"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <!-- 总工办审批 -->
      <template v-if="$hasPermission(['task:jsgl:zgb']) && this.currentStatus">
        <el-row style="margin-top: 30px;">
          <el-col :span="24">
            <el-form-item label="总工办审批意见：" prop="zgbOptions">
              <el-input :disabled="zgbNode" type="textarea" v-model="form.zgbOptions" placeholder="请输入"
                :rows="4"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="" prop="zgbStatus">
              <el-radio-group :disabled="zgbNode" v-model="form.zgbStatus">
                <el-radio :label="'1'">同意</el-radio>
                <el-radio :label="'2'">不同意</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="审批人：" prop="zgbUserId">
              <el-select ref="zgbUserId" :disabled="zgbNode" filterable v-model="form.zgbUserId" placeholder="请选择"
                style="width: 100%;">
                <el-option v-for="  item   in   userList  " :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审批时间" prop="zgbTime">
              <el-date-picker :disabled="zgbNode" value-format="yyyy-MM-dd HH:mm:ss" v-model="form.zgbTime" type="date"
                style="width: 100%;" placeholder="选择日期时间"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </template>



      <!-- 技术分院领导审批 -->
      <template v-if="$hasPermission(['task:jsgl:fyld']) && this.currentStatus">
        <el-row style="margin-top: 30px;">
          <el-col :span="24">
            <el-form-item label="技术分院领导审批意见：" prop="fyldOptions">
              <el-input :disabled="yldNode" type="textarea" v-model="form.fyldOptions" placeholder="请输入"
                :rows="4"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="" prop="fyldStatus">
              <el-radio-group :disabled="yldNode" v-model="form.fyldStatus">
                <el-radio :label="'1'">同意</el-radio>
                <el-radio :label="'2'">不同意</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="审批人：" prop="fyldUserId">
              <el-select ref="fyldUserId" :disabled="yldNode" filterable v-model="form.fyldUserId" placeholder="请选择"
                style="width: 100%;">
                <el-option v-for="  item   in   userList  " :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审批时间" prop="fyldTime">
              <el-date-picker :disabled="yldNode" value-format="yyyy-MM-dd HH:mm:ss" v-model="form.fyldTime" type="date"
                style="width: 100%;" placeholder="选择日期时间"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <template>
        <el-form-item label="">
          <el-button type="primary" :loading="saveLoading" v-if="saveDisabled" @click="handlerSave">保存</el-button>
          <el-button type="primary" v-if="nextDisabled" :loading="nextLoading" @click="handlerSaveAndNext">提交</el-button>
        </el-form-item>
      </template>
    </el-form>

    <div class="division"></div>
    <!-- 审批日志 -->
    <LogsBox :logsData="lcLogs"></LogsBox>
  </div>
</template>

<script>
import { getAllUserList } from "@/api/system/user";
import { getDeptList } from "@/api/project/project";
import { queryTaskList, addTask, editTask, launchTask, ApproveTask, getJsProgress } from "@/api/project/task";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import userSelect from "@/components/userSelect/index";
import { downloadGet } from '@/utils/request'
import LogsBox from "@/components/LogsBox";

export default {
  components: { Treeselect, userSelect, LogsBox },
  props: {
    pageType: {
      type: String,
      require: true
    },
  },
  dicts: ['xmgl_process_status'],
  data() {
    return {
      pageLoading: false,
      saveLoading: false,
      nextLoading: false,
      lcLogs: [],
      fileList: [],
      userList: [],
      deptTreeList: [],
      refreshPage: true,
      form: {
        scbmUserId: undefined,
        promoterDeptId: undefined,
        requestTime: null
      },
      rules: {
        promoterDeptId: [{ required: true, message: '请选择部门', trigger: 'change' }],

        scbmOptions: [{ required: true, message: '请填写审批意见', trigger: 'blur' }],
        scbmUserId: [{ required: true, message: '请选择审批人', trigger: 'blur' }],
        scbmStatus: [{ required: true, message: '请选择审批状态', trigger: 'blur' }],
        scbmTime: [{ required: true, message: '请选择审时间', trigger: 'blur' }],

        zgbOptions: [{ required: true, message: '请填写审批意见', trigger: 'blur' }],
        zgbUserId: [{ required: true, message: '请选择审批人', trigger: 'blur' }],
        zgbTime: [{ required: true, message: '请选择审时间', trigger: 'blur' }],
        zgbStatus: [{ required: true, message: '请选择审批状态', trigger: 'blur' }],

        fyldOptions: [{ required: true, message: '请填写审批意见', trigger: 'blur' }],
        fyldUserId: [{ required: true, message: '请选择审批人', trigger: 'blur' }],
        fyldTime: [{ required: true, message: '请选择审时间', trigger: 'blur' }],
        fyldStatus: [{ required: true, message: '请选择审批状态', trigger: 'blur' }],
      },
      currenrNode: '', // 当前节点
      currentStatus: '', // 当前用户所在节点状态
      completeStatus: '' // 整个任务的状态
    };
  },
  watch: {
    pageType: {
      immediate: true,
      handler(n) {
        this.setDefault(); // 设置默认值
        this.queryTaskList();
      }
    }
  },
  created() {
    this.getAllUserList();
    this.getDeptList();
  },
  computed: {
    // this.currentStatus === '1' 当前节点已经完成
    //  this.completeStatus === '3' 整个任务状态已经完成
    // 申请人控件禁用状态
    sqrNode() {
      if (this.completeStatus === '3') return true; // 完成
      if (!this.$hasPermission(['task:jsgl:lanuch']) || this.completeStatus === '1') return true;
      if (this.completeStatus === '0') return false;
      if (this.completeStatus === '5' && this.$hasPermission(['task:jsgl:lanuch'])) return false; // 退回
    },
    scbmNode() {
      if (this.completeStatus === '3') return true;
      if (['1', '2'].includes(this.currentStatus) && this.$hasPermission(['task:jsgl:scbmfzr'])) return true; // 生产部门审核完成
      if (!this.$hasPermission(['task:jsgl:scbmfzr'])) return true; // 当前部门不是生产部门
    },
    zgbNode() {
      if (this.completeStatus === '3') return true;
      if (['1', '2'].includes(this.currentStatus) && this.$hasPermission(['task:jsgl:zgb'])) return true; // 总工办审核完成
      if (!this.$hasPermission(['task:jsgl:zgb'])) return true; // 当前部门不是总工办
    },
    yldNode() {
      if (this.completeStatus === '3') return true;
      if (['1', '2'].includes(this.currentStatus) && this.$hasPermission(['task:jsgl:fyld'])) return true; // fyld审核完成
      if (!this.$hasPermission(['task:jsgl:fyld'])) return true; // 当前用户不是fyld权限
      return false;
    },
    // 保存按钮
    saveDisabled() {
      if (this.completeStatus === '3') {
        return false
      } else if (!this.currentStatus) { // 还没开始流程
        if (this.$hasPermission(['task:jsgl:lanuch'])) {
          return true
        } else {
          return false
        }
      } else if (this.completeStatus === '5' && this.$hasPermission(['task:jsgl:lanuch'])) {
        return true
      } else if (this.currentStatus === '1' && this.$hasPermission(['task:jsgl:lanuch'])) {
        return false;
      } else if (this.judgmentProcess(this.$store.state.user.roles)) {
        return true
      }
    },
    // 提交按钮
    nextDisabled() {
      if (this.completeStatus === '3') {
        return false
      } else if ((!this.currentStatus || this.currentStatus === '0') && this.$hasPermission(['task:jsgl:lanuch'])) {
        // 新增
        return true
      } else if (this.currentStatus === '1' && this.$hasPermission(['task:jsgl:lanuch'])) { // 已经提交
        return false;
      } else if (this.completeStatus === '5' && this.$hasPermission(['task:jsgl:lanuch'])) { // 只有未完成和有提交权限
        return true; // 退回
      }
    }
  },

  methods: {
    // 设置默认值
    setDefault() {
      this.form.scbmUserId = this.$store.state.user.id;
      this.form.scbmTime = this.$dayjs().format("YYYY-MM-DD HH:mm:ss");
      this.form.zgbUserId = this.$store.state.user.id;
      this.form.zgbTime = this.$dayjs().format("YYYY-MM-DD HH:mm:ss");
      this.form.fyldUserId = this.$store.state.user.id;
      this.form.fyldTime = this.$dayjs().format("YYYY-MM-DD HH:mm:ss");
    },
    // 刷新页面
    refreshPageFn() {
      this.refreshPage = false;
      this.$nextTick(() => {
        this.refreshPage = true;
      });
    },
    // 获取所有用户
    async getAllUserList() {
      const res = await getAllUserList();
      this.userList = res.data;
    },
    // 获取详情
    async queryTaskList() {
      this.pageLoading = true;
      const res = await queryTaskList(this.$route.query.taskId, this.pageType);
      if (res?.rows.length === 1) {
        this.form = res.rows[0];
        // 材料回显示
        this.fileList = res.rows[0]?.annexs;
        this.completeStatus = res.rows[0]?.status;
        this.getApproveLogs();
      } else if (res?.rows.length > 1) {
        let target = res.rows.find(item => ['0', '1', '3'].includes(item.status));
        // 说明有退回，新增了申请的情况
        if (target) {
          this.fileList = target?.annexs;
          this.completeStatus = target?.status;
          this.form = target;
        } else {
          // 退回还没有重新新增
          this.form = res.rows.at(-1);
          this.fileList = res.rows.at(-1).annexs;
          this.completeStatus = res.rows.at(-1).status;
        }
        this.getApproveLogs();
      } else {
        // 设置默认值
        this.$nextTick(() => {
          this.form.promoterDeptId = this.$store.state.user.deptId;
          this.form.promoterId = this.$store.state.user.id;
          this.form.requestTime = this.$dayjs().format("YYYY-MM-DD HH:mm:ss");
        })
      }
      this.pageLoading = false;
    },
    // 获取流程日志
    async getApproveLogs() {
      const res = await getJsProgress(this.$route.query.taskId, this.pageType);
      if (res.data.length) {
        this.lcLogs = res.data.sort((a, b) => {
          if (a.doneTime === null) return 1;
          if (b.doneTime === null) return -1;
          return new Date(a.doneTime).getTime() - new Date(b.doneTime).getTime();
        });
        let target = res.data.find(item => item.status === "2");
        if (target === undefined) {   // 不存在退回
          // 因为第一个流程没有返回wfActivityKey，只有这么判断
          if (this.$store.state.user.roles.includes('scbm_rwfzr')) {
            this.currentStatus = this.lcLogs.find(item => !item.wfActivityKey)?.status;
          } else {
            this.currentStatus = this.lcLogs.find(item => this.$store.state.user.roles.includes(item.wfActivityKey))?.status; // 当前用户的节点状态
          }
          this.currenrNode = this.lcLogs.find(item => item.status === '0')?.wfActivityKey;  // 当前/下一步节点对象name
        } else {
          // 存在退回
          if (this.completeStatus === '5') {
            this.currenrNode = null;
            this.currentStatus = '';
          } else {
            this.currenrNode = this.lcLogs.find(item => item.status === '0')?.wfActivityKey;  // 当前/下一步节点对象name
            if (this.$store.state.user.roles.includes('scbm_rwfzr')) { // 申请节点
              if (this.completeStatus === '0') {
                this.currentStatus = "";
              } else {
                this.currentStatus = this.lcLogs.find(item => !item.wfActivityKey)?.status;
              }
            } else {
              if (this.$store.state.user.roles.includes(this.currenrNode)) {
                // 是当前节点
                this.currentStatus = this.lcLogs.find(item => this.$store.state.user.roles.includes(item.wfActivityKey) && item.status === '0' && item.status !== '2')?.status; // 当前用户的节点状态
              } else {
                // 当前节点已经完成
                this.currentStatus = this.lcLogs.find(item => this.$store.state.user.roles.includes(item.wfActivityKey) && item.status === '1' && item.status !== '2')?.status; // 当前用户的节点状态
              }
            }
          }
        }
        // console.log('this.currentStatus', this.currentStatus)
        // console.log('this.currenrNode', this.currenrNode)
        if (this.currentStatus === '0') {
          this.setDefault();
          return
        }


        // 审批流程赋值
        let zgb = res.data.find(item => item.wfActivityKey === 'zgb_jsgly' && item.status === '1');
        let scbm = res.data.find(item => item.wfActivityKey === 'scbm_fzr' && item.status === '1');
        let fyld = res.data.find(item => item.wfActivityKey === 'yld_fgjs' && item.status === '1');
        if (scbm) {
          this.form.scbmUserId = scbm?.approverId;
          this.form.scbmTime = scbm?.startTime;
          this.form.scbmOptions = scbm?.opinions;
          this.form.scbmStatus = scbm?.status;
        }

        if (zgb) {
          this.form.zgbUserId = zgb?.approverId;
          this.form.zgbTime = zgb?.startTime;
          this.form.zgbOptions = zgb?.opinions;
          this.form.zgbStatus = zgb?.status;
        }

        if (fyld) {
          this.form.fyldUserId = fyld?.approverId;
          this.form.fyldTime = fyld?.startTime;
          this.form.fyldOptions = fyld?.opinions;
          this.form.fyldStatus = fyld?.status;
        }
      }
    },
    // 获取部门树结构
    async getDeptList() {
      const res = await getDeptList();
      this.deptTreeList = res.data
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.value,
        label: node.label,
        children: node.children
      };
    },
    // 判断当前用户所在流程是否完成，然后做禁用处理
    judgmentProcess(roles) {
      if (!this.lcLogs.length) return true;
      let target = this.lcLogs?.find(item => {
        // 第一个流程没有wfActivityKey
        if (item.wfActivityKey === "") {
          if (item.status === '1') return false
          return true
        } else {
          return roles.includes(item.wfActivityKey) && item.status === '0';
        }
      })
      return target?.status === '0' && target.wfNameKey.indexOf(this.pageType) > -1  // 当前用户未完成
    },
    //附件移除
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    // 上传前控制
    beforeAvatarUpload(file, fileList) {
      const isLt2M = file.size / 1024 / 1024 < 100;
      if (!isLt2M) {
        this.$message.error(`上传图片大小不能超过100MB!`);
      }
      return isLt2M;
    },
    // 材料改变
    handleChange(file, fileList) {
      const res = this.beforeAvatarUpload(file, fileList);
      if (!res || fileList.length >= 2) {
        fileList.shift();
      }
      this.fileList = fileList;
    },
    // 下载附件
    downLoad(file) {
      return downloadGet(this.downBaseUrl + file.path, {}, file.name);
    },

    // 发起流程
    handlerSaveAndNext() {
      if (!this.form?.id) return this.$modal.msgError('请先保存,再发起流程！');
      this.$refs.form.validate(async (vaild) => {
        if (vaild) {
          this.nextLoading = true;
          try {
            const res = await launchTask(this.$route.query.taskId, this.pageType, this.form.id);
            if (res.code === 200) {
              this.$modal.msgSuccess('提交成功');
              this.queryTaskList();
              this.refreshPageFn();
            }
          } catch (error) { }
          finally {
            this.nextLoading = false;
          }
        } else {
          this.$modal.msgError('请填写完完整信息！');
        }
      })
    },
    // 发起节点保存数据
    async save() {
      if (this.fileList.length === 0) return this.$modal.msgError('请上传附件');
      this.saveLoading = true;
      // 上传材料
      try {
        if (this.fileList[0]?.status !== 'success') {
          let result = await this.fileUpload(this.fileList);
          this.fileList = [{
            size: result.size,
            status: result.status,
            name: result.originalFilenames[0],
            path: result.fileNames[0],
            id: result.attachmentIds[0]
          }]
        }
        this.form.annexIdValues = this.fileList.map(item => item.id);
        if (this.form.id && this.completeStatus !== '5') { // 5表示退回
          await editTask(this.$route.query.taskId, this.pageType, this.form);
          this.$modal.msgSuccess('修改成功');
        } else {
          await addTask(this.$route.query.taskId, this.pageType, this.form);
          this.$modal.msgSuccess('保存成功');
        }
      } catch (error) { }
      finally {
        this.saveLoading = false;
      }
    },
    // 审批接口
    async scbmApprove() {
      // 根据当前日志判断当前流程，获取控件值
      let params = {}
      // 生产负责人审批
      if (this.currenrNode === 'scbm_fzr') {
        params = {
          time: this.form.scbmTime,
          userId: this.form.scbmUserId,
          opinions: this.form.scbmOptions,
          status: this.form.scbmStatus,
          userName: this.$refs.scbmUserId.selected.label
        }
      } else if (this.currenrNode === 'zgb_jsgly') {
        // 总工办审批
        params = {
          time: this.form.zgbTime,
          userId: this.form.zgbUserId,
          opinions: this.form.zgbOptions,
          status: this.form.zgbStatus,
          userName: this.$refs.zgbUserId.selected.label
        }
      } else if (this.currenrNode === 'yld_fgjs') {
        // 院领导审批
        params = {
          time: this.form.fyldTime,
          userId: this.form.fyldUserId,
          opinions: this.form.fyldOptions,
          status: this.form.fyldStatus,
          userName: this.$refs.fyldUserId.selected.label
        }
      }
      const res = await ApproveTask(this.$route.query.taskId, this.pageType, this.form.id, params);
      if (res.code === 200) {
        this.$modal.msgSuccess('审批成功');
      }
    },
    // 保存和审批
    handlerSave() {
      this.$refs.form.validate(async (vaild) => {
        if (vaild) {
          // 发起流程
          if (this.$hasPermission(['task:jsgl:lanuch']) || this.completeStatus === '5') {
            // 只有申请权限才有保存接口
            await this.save();
          } else {
            if (!this.form.id) return this.$modal.msgError('请先发起流程在审批！');
            this.scbmApprove();
            // 重新获取数据
            await this.getApproveLogs();
          }
          this.queryTaskList();
          this.refreshPageFn();
        }
      })
    },
  },
};
</script>

<style lang="scss" scoped>
.technicalDesign {
  width: 100%;

  .logs {
    width: 100%;
    border: 1px solid #666;
    color: #999;

    .logsTitle {
      width: 100%;
      height: 60px;
      line-height: 60px;
      padding-left: 20px;
      border-bottom: 2px solid #999;
    }

    .logsContent {
      padding-top: 30px;

      // ::v-deep .el-timeline-item__wrapper {
      //   height: 120px;
      // }

      .opinions {
        width: 600px;
        height: 50px;
        line-height: 50px;
        background: #f2f2f2;
        border-radius: 4px;
        padding-left: 10px;
      }
    }
  }
}

.line {
  width: 100%;
  height: 2px;
  background: #999;
  margin-bottom: 20px;
}

.division {
  width: 12000px;
  height: 50px;
  background-color: #F5F7FA;
}
</style>
